<template><div>

<form action="/">
  <van-search
    v-model="searchText"
    show-action
    placeholder="请输入搜索关键词"
    @search="onSearch"
    @cancel="onCancel"
    @focus="isResultShow=false"
  />
</form>
<SearchResult v-if="isResultShow" :searchText="searchText"></SearchResult>
<SearchSuggestion v-else-if="searchText" :search-text="searchText" @search="onSearch"></SearchSuggestion>
<SearchHistory :searchHistory="searchHistory"  @search="onSearch" v-else ></SearchHistory>


</div></template>

<script setup>
import  SearchHistory    from "./components/search-history.vue"
import  SearchSuggestion    from "./components/search-suggestion.vue"
import  SearchResult    from "./components/search-result.vue"
import {setItem,getItem} from "../../utils/storage"
import { ref,watch } from 'vue';
const searchText = ref('');
let searchHistory=ref(getItem("TOUTIAO_SEARCH")||[])
let isResultShow=ref(false)

function onSearch(search){
searchText.value=search

//保存搜索条件
const index =searchHistory.value.indexOf(search)
if(index!==-1){
  searchHistory.value.splice(index,1)
}
searchHistory.value.unshift(search)
    isResultShow.value=true
}

watch(searchHistory,(newValue,oldValue)=>{
   setItem("TOUTIAO_SEARCH",newValue)
})
function onCancel(){}
</script>